package security.key;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;

import javax.crypto.SecretKey;



public class KeyManager {
	
	private static KeyManager instance;
	private KeyStore keyStore;
	private SecretKey key;
	
	
	private KeyManager() throws KeyStoreException{
		keyStore = KeyStore.getInstance("JKS");
	}
	
	public KeyManager getKeyManager() throws KeyStoreException
	{
		if(instance == null)
			instance = new KeyManager();
		return instance;
	}
	
	public SecretKey getKey(){
		if(key ==null)
			throw new RuntimeException("No key specified");
		
		return key;
	}
	
		
	
	
	/*public SecretKey creatBlowFishKey()
	{
		return new SecretKey();
	}
	*/
	/*
	 * inspirer par http://stackoverflow.com/questions/3027273/how-to-store-and-load-keys-using-java-security-keystore-class
	 * certificat is not usfull for our key type
	 */
	public void storekey(String path,String keyname,char[] keystorePassword,char[] passwordForKey,Certificate[] certificat) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException
	{
		keyStore.setKeyEntry("keyAlias", key, passwordForKey, certificat);
		OutputStream writeStream = new FileOutputStream(path);
		keyStore.store(writeStream, keystorePassword);
		writeStream.close();

	}
	
	public void loadKey(String path,char[] keystorePassw,char[] passwordForKey) throws UnrecoverableKeyException, KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException{
		InputStream readStream = new FileInputStream(path);
		keyStore.load(readStream, keystorePassw);
		key = (SecretKey) keyStore.getKey("keyAlias", passwordForKey);
		readStream.close();
		
	}
	
	
}
